package com.dynabook.ems.disruptor.BorrowUpdate;

import com.dynabook.ems.model.entity.EmsBorrowHistory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class BorrowUpdateDisruptorProducer {

    @Resource
    private Disruptor<BorrowUpdateEvent> borrowUpdateDisruptor;

    public void pushBorrowHistoryBatch(List<EmsBorrowHistory> borrowHistoryList) {
        RingBuffer<BorrowUpdateEvent> ringBuffer = borrowUpdateDisruptor.getRingBuffer();
        long next = ringBuffer.next();
        try {
            BorrowUpdateEvent event = ringBuffer.get(next);
            // 创建新副本，避免引用外部列表导致数据被修改
            List<EmsBorrowHistory> copy = new ArrayList<>(borrowHistoryList);
            event.setBorrowHistoryList(copy);
            log.info("推送借用历史数据批次，数量: {}", copy.size());
        } finally {
            ringBuffer.publish(next);
        }
    }

    @PreDestroy
    public void shutdown() {
        borrowUpdateDisruptor.shutdown();
    }
}